<template>
  <!--id="myPrint" 指定导出的页面vue-print-nb插件的调用  -->
  <div class="test" id="myPrint">
  
    <div class="select">

      <el-button @click="handleClickExport">确认导出</el-button>
      <el-button @click="handleClickExportSheet">确认多个sheet导出</el-button>
      <!-- @click="printPreview" -->
      <el-button v-print="printObj">预览打印</el-button>
      <el-select v-model="value" placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
    </div>
    <div>
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="date" label="日期" width="180">
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="address" label="地址"> </el-table-column>
      </el-table>
    </div>

    <div v-for="(data, index) in tableDataList" :key="index">
      {{ `第${index + 1}张` }}
      <el-table :data="data" stripe style="width: 100%">
        <el-table-column prop="date" label="日期" width="180">
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="address" label="地址"> </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import dayjs from "dayjs";
import print from "vue-print-nb";

import {
  export_json_to_excel,
  export_season_to_excel,
} from "@/vendor/Export2Excel.js";

export default {
  data() {
    return {
      // 导出配置项
      printObj: {
        id: "myPrint", // 这里是要打印元素的ID
        popTitle: "&nbsp", // 打印的标题(防止出现undefined的问题)
        extraCss: "", // 打印可引入外部的一个 css 文件
        // extraHead: "", // 打印头部文字 可传入内联样式
        extraHead: ` <span style="color:blue">${dayjs().format(
          "YYYY-MM-DD HH:mm:ss"
        )}</span>`,
      },

      // 多选框
      options: [
        {
          value: "1",
          label: "导出本表",
        },
        {
          value: "2",
          label: "导出全部",
        },
      ],
      value: "1",
      // 表格
      tableData: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 ",
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1517 ",
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1519 ",
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1516 ",
        },
      ],
      // 多个sheet导出excel
      tableDataList: [
        [
          {
            date: "2016-05-02",
            name: "王",
            address: "上海市普陀区金沙江路 1518 ",
          },
          {
            date: "2016-05-04",
            name: "虎",
            address: "上海市普陀区金沙江路 1517 ",
          },
          {
            date: "2016-05-01",
            name: "王小",
            address: "上海市普陀区金沙江路 1519 ",
          },
          {
            date: "2016-05-03",
            name: "王小虎",
            address: "上海市普陀区金沙江路 1516 ",
          },
        ],
        [
          {
            date: "2016-05-02",
            name: "历史",
            address: "上海市普陀区金沙江路 1518 ",
          },
          {
            date: "2016-05-04",
            name: "牛逼",
            address: "上海市普陀区金沙江路 1517 ",
          },
          {
            date: "2016-05-01",
            name: "王小虎",
            address: "上海市普陀区金沙江路 1519 ",
          },
          {
            date: "2016-05-03",
            name: "test",
            address: "上海市普陀区金沙江路 1516 ",
          },
        ],
        [
          {
            date: "2016-05-02",
            name: "哈哈哈",
            address: "上海市普陀区金沙江路 1518 ",
          },
          {
            date: "2016-05-04",
            name: "嗷嗷嗷",
            address: "上海市普陀区金沙江路 1517 ",
          },
          {
            date: "2016-05-01",
            name: "哦哦哦",
            address: "上海市普陀区金沙江路 1519 ",
          },
          {
            date: "2016-05-03",
            name: "婆婆",
            address: "上海市普陀区金沙江路 1516 ",
          },
        ],
      ],
    };
  },
  methods: {
    // 后端返回二进制流的
    async getDomwBlobFile(name) {
      let res = await axios({
        url: "http://192.168.8.232:8002/res/data/getResTemplate",
        method: "get",
        responseType: "blob",
      });
      console.log(res?.data);
      // 下载文件
      let blob;
      let fileName = "";
      if (res instanceof Blob) {
        blob = new Blob([res]);
        if (isALLFile && name) {
          fileName = name;
        } else {
          if (name) {
            fileName = `${name}.xlsx`;
          } else {
            fileName = `${dayjs().format("YYYY-MM-DD HH_mm_ss")}.xlsx`;
          }
        }
      } else {
        blob = new Blob([res.data]);
        // 从响应头中获取文件名称
        let fileNameResponse;
        const contentDisposition = res.headers["content-disposition"];
        if (contentDisposition) {
          // 正则获取filename的值
          const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
          const matches = filenameRegex.exec(contentDisposition);
          if (matches != null && matches[1]) {
            fileNameResponse = matches[1].replace(/['"]/g, "");
            fileNameResponse = decodeURI(fileNameResponse);
          }
          fileName = fileNameResponse;
          console.log(fileNameResponse);
        } else {
          if (name) {
            fileName = `${name}.xlsx`;
          } else {
            fileName = `${dayjs().format("YYYY-MM-DD HH_mm_ss")}.xlsx`;
          }
        }
      }
      if ("download" in document.createElement("a")) {
        // 非IE下载
        const elink = document.createElement("a");
        elink.download = fileName;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName);
      }
    },
    // 后端返回连接(请求接口后拿到文件的链接)
    getDownFileExcel(fileUrl, fileName = "测试excel") {
      let name = fileUrl.lastIndexOf(".");
      let suffix = fileUrl.substring(name); //截取后缀名
      if ("download" in document.createElement("a")) {
        // 非IE下载
        const elink = document.createElement("a");
        elink.download = fileName;
        elink.setAttribute("download", `${suffix}`);
        elink.style.display = "none";
        elink.href = url;
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName);
      }
    },
    // 导出列表格式化数据的方法
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    // 前端生成excel(单个excel)
    generateExcel() {
      // 表头
      const tHeader = ["时间", "名称", "地址"];
      // table表格中对应的属性名
      const filterVal = ["date", "name", "address"];
      // 表格绑定数据转json
      const data = this.formatJson(filterVal, this.tableData);
      export_json_to_excel(
        tHeader,
        data,
        "测试数据" + new Date().toLocaleDateString()
      ); // 对应下载文件的名字
    },
    handleClickExport() {
      console.log("执行导出");
      this.generateExcel();
    },

    // 导出绩效信息excel(多个同类型的,多类型应对表头与属性重新调整应该更改为动态)
    exportSeason() {
      // 表头
      const tHeader = ["时间", "名称", "地址"];
      // table表格中对应的属性名
      const filterVal = ["date", "name", "address"];
      let datas = [];
      let sheets = [];
      this.tableDataList.forEach((item, index) => {
        // 表格绑定数据转json
        datas.push(this.formatJson(filterVal, item));
        sheets.push(`第${index + 1}季度绩效`);
      });
      export_season_to_excel(
        tHeader,
        datas,
        "测试多个sheef" + new Date().toLocaleDateString(),
        sheets
      ); // 对应下载文件的名字
    },

    // 导出多个sheet
    handleClickExportSheet() {
      this.exportSeason();
    },
    // 预览打印
    printPreview() {
      // 可做图片导出
    },
   
  },
  created() {
    // setTimeout(()=>{
    // 调用浏览器设备不能指定打印区域
    //  window.print();
    // },3000)
    // this.getDomwBlobFile();
  },
  
  // 局部注册指令(也可挂入到全局)
  directives: {
    print,
  },
};
</script>


<style>
/* 处理vue-print-nb的分页,若是打印隐藏的盒子则需在这个盒子外面包裹一个div,并将其隐藏,实际打印的盒子不隐藏 */
  @media print {
    @page {
      size:  auto;
    }
    body, html {
      height: auto !important;
    }
  }
</style>
<style scoped>
.select {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
}

/* 去掉页眉页脚 */
@page {
  size: auto;
  margin: 0mm;
}
/* 打印內容不自动换行问题 */
.procedure {
  word-wrap: break-word;
}

@media print {
}


</style>
